package com.yogee.topseller.activity.login.view.impl;

import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.igexin.sdk.PushManager;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.loading.CustomProgressDialog;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.AppManager;
import com.yogee.core.utils.LogUtils;
import com.yogee.core.utils.SharedPreferencesUtils;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.MainActivity;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.MainActivity1;
import com.yogee.topseller.activity.base.HttpActivity;
import com.yogee.topseller.activity.login.model.bean.SMSbean;
import com.yogee.topseller.activity.login.model.bean.SendSMSBean;
import com.yogee.topseller.activity.login.model.bean.UserBean;
import com.yogee.topseller.activity.login.presenter.LoginPresenter;
import com.yogee.topseller.activity.login.presenter.ResetPswPresenter;
import com.yogee.topseller.activity.login.view.ILoginView;
import com.yogee.topseller.activity.login.view.IResetPswView;
import com.yogee.topseller.bean.ProductInfoBean;
import com.yogee.topseller.bean.ResultBean;
import com.yogee.topseller.http.Config;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.utils.Constants;
import com.yogee.topseller.view.ClearEditText;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends HttpActivity implements ILoginView,IResetPswView{

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.cet_phone)
    ClearEditText cetPhone;
    @BindView(R.id.cet_pwd)
    ClearEditText cetPWD;
    @BindView(R.id.tv_forget_pwd)
    TextView tvForgetPwd;
    @BindView(R.id.login_login)
    TextView loginLogin;
    @BindView(R.id.login_switch)
    TextView loginSwitch;
    @BindView(R.id.we_chat)
    LinearLayout weChat;
    @BindView(R.id.bottom)
    LinearLayout bottom;
    @BindView(R.id.sina)
    LinearLayout sina;
    @BindView(R.id.qq)
    LinearLayout qq;
    @BindView(R.id.tv_login_pwd)
    TextView tv_login_pwd;
    @BindView(R.id.ll_login_pwd)
    LinearLayout ll_login_pwd;
    @BindView(R.id.ll_login_by_verification)
    LinearLayout ll_login_by_verification;
    @BindView(R.id.verification_cet_phone)
    ClearEditText verification_cet_phone;
    @BindView(R.id.verification_cet_pwd)
    ClearEditText verification_cet_pwd;
    @BindView(R.id.get_code)
    TextView get_code;


    // 1:直接关闭当前Activity
//    private String startFlag;

    private UMShareAPI mShareAPI = null;
    // 三方类型 1:微信；2：QQ；3：微博
    private String type = "";
    CustomProgressDialog pd = null;
    // ture：密码登录 false：验证码登录
    private boolean flag = true;

    private String openid;
    private String headerUrl;
    private String name;
    private String sex;
    private String unionid;
    LoginPresenter loginPresenter;

    private String phone1="",phone2="";

    ResetPswPresenter resetPswPresenter;

    //生成一个随机数
    private int mRadomNumber = 0;
    // 倒计时
    private CountDownTimer timer;


    @Override
    protected void initView() {
        MobclickAgent.onEvent(LoginActivity.this, "ma_loginBtn");
        mRadomNumber = AppUtil.getRandomNumber(6);

        loginPresenter = new LoginPresenter(this);

        resetPswPresenter = new ResetPswPresenter(this);
//        startFlag = getIntent().getStringExtra("startFlag");
        mShareAPI = UMShareAPI.get(this);
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        UMShareAPI.get(this).setShareConfig(config);
        if (AppUtil.isWeiBoClientAvailable(this)) {
            bottom.setVisibility(View.VISIBLE);
            sina.setVisibility(View.GONE);
        }
        if (AppUtil.isWeixinAvilible(this)) {
            bottom.setVisibility(View.VISIBLE);
            weChat.setVisibility(View.VISIBLE);
        }
        if (AppUtil.isQQClientAvailable(this)) {
            bottom.setVisibility(View.VISIBLE);
            qq.setVisibility(View.GONE);
        }
        verification_cet_pwd.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                verification_cet_pwd.setFocusable(true);
                verification_cet_pwd.setFocusableInTouchMode(true);
                return false;
            }
        });
        verification_cet_pwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String code = verification_cet_pwd.getText().toString().trim();
                if(code.length()>=6){
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

                }

            }
        });
    }
                                                                                                                                        
    @Override
    protected int getLayoutId() {
        return R.layout.activity_login_pwd;
    }

    @Override
    public Boolean validate() {
        if(flag){
            if (cetPhone.getText().length() == 0) {
                ToastUtils.showToast(this, "请填写电话");
                return false;
            } else if (cetPhone.getText().length() != 11) {
                ToastUtils.showToast(this, "请填写11位手机号");
                return false;
            } else if (cetPWD.getText().toString().length() == 0) {
                ToastUtils.showToast(this, "请填写密码");
                return false;
            } else if (cetPWD.getText().toString().length() < 6 || cetPWD.getText().toString().length() > 20) {
                ToastUtils.showToast(this, "请填写6-20位密码");
                return false;
            } else {
                return true;
            }
        }else{
            if (verification_cet_phone.getText().length() == 0) {
                ToastUtils.showToast(this, "请填写电话");
                return false;
            } else if (verification_cet_phone.getText().length() != 11) {
                ToastUtils.showToast(this, "请填写11位手机号");
                return false;
            } else if (verification_cet_pwd.getText().toString().length() == 0) {
                ToastUtils.showToast(this, "请填写验证码");
                return false;
            }
//            else if (!verification_cet_pwd.getText().toString().equals(String.valueOf(mRadomNumber))) {
//                ToastUtils.showToast(this, "验证码输入错误");
//                return false;
//            }
            else {
                return true;
            }
        }

    }

    @Override
    public void loginSuccess() {
//        if (TextUtils.isEmpty(startFlag)) {
//        }
        if(flag){
            MobclickAgent.onEvent(LoginActivity.this, "ma_loginBtn_sure_sucess");
        }else{
            MobclickAgent.onEvent(LoginActivity.this, "yzm_loginBtn_sure_sucess");
        }
        AppManager.finishAllActivity();
        startActivity(new Intent(this, MainActivity1.class));

        finish();
    }


    private void resetLoginButton(Boolean flag) {
        if (flag) {
            pd = CustomProgressDialog.createDialog(this);
            sina.setClickable(false);
            weChat.setClickable(false);
            qq.setClickable(false);
        } else {

            if (pd != null)
                pd.dismiss();

            sina.setClickable(true);
            weChat.setClickable(true);
            qq.setClickable(true);
        }
    }

    private void checkBindPhone(final String openid,final String myunionid,final String name,final String headerUrl,final String deviceId){
        HttpManager.getInstance().otherLoginopenId(myunionid).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<UserBean>() {
            @Override
            public void onNext(UserBean o) {
                if("0".equals(o.getFlas())){
                    MobclickAgent.onEvent(LoginActivity.this, "wx_reg_phone");
                    Intent intent = new Intent();
                    intent.setClass(LoginActivity.this, ForgetPswActivity.class);
                    intent.putExtra("flag",Constants.FLAG_AUTH);
                    intent.putExtra("openid",openid);
                    intent.putExtra("unionid",myunionid);
                    intent.putExtra("name",name);
                    intent.putExtra("headerUrl",headerUrl);
                    intent.putExtra("deviceId",deviceId);
                    startActivity(intent);
                }else{
                    MobclickAgent.onEvent(LoginActivity.this, "wx_login_success");
                    AppUtil.saveUserInfo(LoginActivity.this,o);
                    AppManager.finishAllActivity();
                    startActivity(new Intent(LoginActivity.this, MainActivity1.class));
                    finish();
//                    loginSuccess();
                }
            }
        }, this));
    }

    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {

            LogUtils.e("test", "onStart");
        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {

            LogUtils.e("test", "onComplete");
            LogUtils.e("test", data.toString());
            openid = data.get("openid");
            unionid = data.get("unionid");
            headerUrl = data.get("iconurl");
            name = data.get("name");
            sex = "男".equals(data.get("gender")) ? "1" : "0";

            resetLoginButton(false);
            //第三方登陆 获取相关个人信息
            TelephonyManager telephonyManager = (TelephonyManager) getSystemService(LoginActivity.this.TELEPHONY_SERVICE);//获取CID
//            loginPresenter.otherLogin(openid, name, headerUrl, telephonyManager.getDeviceId());

            checkBindPhone(openid,unionid, name, headerUrl, telephonyManager.getDeviceId());
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            LogUtils.e("test", "onError");
            resetLoginButton(false);
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            LogUtils.e("test", "onCancel");
            resetLoginButton(false);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.e("test", "onActivityResult");
        mShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }



    @Override
    public void checkCode(SMSbean smSbean) {
        if (Integer.parseInt(smSbean.getError_code()) == 0) {
            countDownTimer();
            ToastUtils.showToast(this, "验证码已经发送");
        } else {
            get_code.setClickable(true);
            ToastUtils.showToast(this, smSbean.getError_code() + ":" + smSbean.getReason());
        }
    }

    @OnClick({R.id.back, R.id.tv_forget_pwd, R.id.login_login, R.id.login_switch, R.id.we_chat, R.id.qq, R.id.sina,R.id.tv_login_pwd,R.id.login_title,R.id.get_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
//                onBackPressed();
                try{
                    AppManager.finishActivity(ForgetPswActivity.class);
                }catch(Exception e){

                }
                finish();
                break;
            case R.id.tv_forget_pwd:
                if (AppUtil.isFastDoubleClick(500)) {
                    return;
                }

                MobclickAgent.onEvent(LoginActivity.this, "forget_Btn");
                startActivity(new Intent(LoginActivity.this, ForgetPswActivity.class).putExtra("flag", Constants.FLAG_FORGETPASSWORD));
                break;
            case R.id.login_login:
                if (AppUtil.isFastDoubleClick(1000)) {
                    return;
                }
                if(flag){
                    MobclickAgent.onEvent(LoginActivity.this, "ma_loginBtn_sure");
                }else{
                    MobclickAgent.onEvent(LoginActivity.this, "yzm_loginBtn_sure");
                }
                if (validate()) {
                    if(flag){
                        LogUtils.e("登陆","密码登陆");
                        loginPresenter.login(cetPhone.getText().toString(), cetPWD.getText().toString(), Config.LOGIN_BY_PWD, (String) SharedPreferencesUtils.get(this, "cid", "0"),"",Constants.CODE_LOGIN);
                    } else{
                        LogUtils.e("登陆","验证码登陆");
                        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(this.TELEPHONY_SERVICE);//获取CID
                        // 验证码登录需要参数：phone\code\
                        loginPresenter.login(verification_cet_phone.getText().toString(), "", Config.LOGIN_BY_CHECKCODE, telephonyManager.getDeviceId(),verification_cet_pwd.getText().toString(),Constants.CODE_LOGIN);
                    }

                }
                break;
            //
            case R.id.login_switch:
//                if (AppUtil.isFastDoubleClick(500)) {
//                    return;
//                }
                MobclickAgent.onEvent(LoginActivity.this, "yzm_loginBtn");
                phone1=cetPhone.getText().toString();
                if(flag){
                    flag = false;
                    ll_login_by_verification.setVisibility(View.VISIBLE);
                    ll_login_pwd.setVisibility(View.GONE);
                    loginSwitch.setTextColor(getResources().getColor(R.color.white));
                    tv_login_pwd.setTextColor(getResources().getColor(R.color.hint_color));
                    cetPhone.setText("");
                    cetPWD.setText("");
                    if(phone1.length()==11){
                        verification_cet_phone.setText(phone1);
                        verification_cet_phone.setSelection(phone1.length());
                    }
                }
                break;
//                startActivity(new Intent(LoginActivity.this, LoginCheckcodeActivity.class));
            //
            case R.id.tv_login_pwd:
//                if (AppUtil.isFastDoubleClick(500)) {
//                    return;
//                }
                phone2=verification_cet_phone.getText().toString();
                MobclickAgent.onEvent(LoginActivity.this, "ma_loginBtn");
                if(!flag){
                    flag = true;
                    ll_login_pwd.setVisibility(View.VISIBLE);
                    ll_login_by_verification.setVisibility(View.GONE);
                    tv_login_pwd.setTextColor(getResources().getColor(R.color.white));
                    loginSwitch.setTextColor(getResources().getColor(R.color.hint_color));
                    verification_cet_phone.setText("");
                    verification_cet_pwd.setText("");
                    if(phone2.length()==11){
                        cetPhone.setText(phone2);
                        cetPhone.setSelection(phone2.length());
                    }

                }
                break;
            case R.id.sina:
                if (AppUtil.isFastDoubleClick(1000)) {
                    return;
                }
                resetLoginButton(true);
                type = "3";
                mShareAPI.getPlatformInfo(this, SHARE_MEDIA.SINA, umAuthListener);
                break;
            case R.id.we_chat:
                if (AppUtil.isFastDoubleClick(1000)) {
                    return;
                }
                MobclickAgent.onEvent(LoginActivity.this, "wx_loginBtn");
                resetLoginButton(true);
                type = "1";
                mShareAPI.getPlatformInfo(this, SHARE_MEDIA.WEIXIN, umAuthListener);
                break;
            case R.id.qq:
                if (AppUtil.isFastDoubleClick(1000)) {
                    return;
                }
                resetLoginButton(true);
                type = "2";
                mShareAPI.getPlatformInfo(this, SHARE_MEDIA.QQ, umAuthListener);
                break;
            case R.id.login_title:
                if (AppUtil.isFastDoubleClick(500)) {
                    return;
                }
                MobclickAgent.onEvent(LoginActivity.this, "regBtn");
                startActivity(new Intent(LoginActivity.this, ForgetPswActivity.class).putExtra("flag",Constants.FLAG_REGIST));
                finish();
                break;
            case R.id.get_code:
                if (AppUtil.isFastDoubleClick(500)) {
                    return;
                }
                MobclickAgent.onEvent(LoginActivity.this, "get_yzmBtn");
                if ("重新发送".equals(get_code.getText().toString())) {
                    mRadomNumber = AppUtil.getRandomNumber(6);
                }
                if (TextUtils.isEmpty(verification_cet_phone.getText())) {
                    ToastUtils.showToast(this, "请输入手机号");
                    return;
                } else if (!AppUtil.validatePhone(verification_cet_phone.getText().toString())) {
                    ToastUtils.showToast(this, "请输入正确的手机号");
                    return;
                } else {
                    get_code.setTextColor(getResources().getColor(R.color.gray));
//                    get_code.setBackgroundDrawable(getResources().getDrawable(R.drawable.corners5_stroke1gray));
                    get_code.setClickable(false);
//                    loginPresenter.sendSMS(LoginActivity.this, verification_cet_phone.getText().toString(), mRadomNumber);
                    resetPswPresenter.sendSMS(verification_cet_phone.getText().toString(),Constants.CODE_LOGIN);

                }
                break;
            default:
                break;
        }
    }

    public void countDownTimer() {

        timer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                get_code.setText("重新发送" + "(" + millisUntilFinished / 1000 + "s)");
                get_code.setTextColor(getResources().getColor(R.color.gray));
//                get_code.setBackgroundDrawable(getResources().getDrawable(R.drawable.corners5_stroke1gray));
                get_code.setClickable(false);
            }

            @Override
            public void onFinish() {
                get_code.setText("重新发送");
                get_code.setTextColor(getResources().getColor(R.color.theme_color));
//                get_code.setBackgroundDrawable(getResources().getDrawable(R.drawable.corners5_stroke1_theme));
                get_code.setClickable(true);
            }
        };
        timer.start();
    }

    @Override
    public void updatePassword() {

    }

    @Override
    public void updateSuccess() {
        MobclickAgent.onEvent(LoginActivity.this, "get_yzm_success");
        countDownTimer();
    }

    @Override
    public void updateCheckCode(SMSbean smSbean) {

    }

    @Override
    public void showMsg(String msg) {
        ToastUtils.showToast(LoginActivity.this,msg);
        get_code.setText("重新发送");
        get_code.setTextColor(getResources().getColor(R.color.theme_color));
        get_code.setClickable(true);
        if(timer!=null)
            timer.cancel();
    }

    @Override
    protected void onResume() {
        super.onResume();
        resetLoginButton(false);
        MobclickAgent.onResume(this); //统计时长
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}